<template>
  <Spin :spinning="loading" tip="Loading...">
  <div>
    <!-- 预授权审核--车厂-->
    <TopFilter ref="TopFilterss" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="120" @filterChange="changeHandle" @resetChange="resetHandle"></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :fetchapi="fetchapi"
      :datakey="'records'"
      :onColumnsChange="(columns) => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      columnsRef="AuthChecklgr"
    >
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" :click="exportFileBtn.bind()">导出</multiuse-button>
<!--        <multiuse-button size="small" type="primary" :click="batchExamine.bind()" :disabled="disableds">批量审核</multiuse-button>-->
        <!--        <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="batchReject()">批量驳回</multiuse-button>-->
<!--        <multiuse-button size="small" type="primary"  :loading="exportLoading" :click="downloadTemplate.bind()">下载批量驳回模板</multiuse-button>-->
<!--        <multiuse-button size="small" icon="el-icon-upload" :click="showImportFun.bind()" >导入批量驳回</multiuse-button>-->
      </template>
    </FilterTable>

    <!--  服务中心选择 -->
    <BaseDialog :visible.sync="selectDelearFlag" title="服务中心选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <DealerList @close="Delearclose" @save="Delearsave" selectionType="multiple" />
    </BaseDialog>
    <BaseDialog :visible.sync="visibleAdd" :title="'预授权新增'" destroyOnClose width="850px" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <AddForm @close="closeAdd" @save="saveAdd"></AddForm>
    </BaseDialog>
    <BaseDialog :visible.sync="visible" :title="'车型新增'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <vehicle @close="close" @save="save"></vehicle>
    </BaseDialog>
    <Drawer :visible.sync="visibleEdit" :title="'预授权审核'" destroyOnClose width="100%" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <editForm @close="editclose" @save="editsave" :rowData="rowData" :editIds="editIds"></editForm>
    </Drawer>
    <BaseDialog :visible.sync="detailsFlag" :title="'预授权详情'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <DetailPage @close="detailClose" @save="detailSave" :rowData="rowData"></DetailPage>
    </BaseDialog>
    <BaseDialog :visible.sync="showImport" icon="el-icon-upload" :closable="false" title="导入" width="800px" destroyOnClose :containerStyle="{ height: 'calc(100% - 120px)', overflow: 'auto', paddingBottom: '60px' }">
      <importExcel @close="showImport = false" @importclose="auditsave()" url="/api/cms_claimfac/rPPreAuth/importExcel"/>
    </BaseDialog>
  </div>
  </Spin>
</template>
<script>
import DetailPage from './DetailPage.vue';
import vehicle from '@/pages/claimDemage/tools/ModelVehicle.vue';
import editForm from './editForm.vue';
import { getAppId ,getUserOrgId} from '@/assets/js/auth';
import DealerList from '@/pages/claimDemage/tools/DealerList.vue';
import { exportExcelFile } from '@/utils/index';
import { getListByPage, getListForExport, downloadModel,exporturl } from '@/api/claim/factory/AuthQueryFactory';
import importExcel from '@/pages/claimDemage/tools/importExcel.vue';
import { dictionary } from '@/utils/dictMixin';
import { getPositionByUserOrgId ,getDealerAttachListByUser} from '@/api/dictionary';
import moment from "moment";
export default {
  name:'AuthCheckFactory',
  mixins: [dictionary],
  components: {
    vehicle,
    editForm,
    DealerList,
    DetailPage,
    importExcel
  },
  data() {
    return {
      // 非单个禁用
      // single: true,
      single: false,
      // 非多个禁用
      multiple: true,
      dealerList: [],
      selectDelearFlag: false,
      dealerCompanyCode: [],
      dealerData: [],
      selectDealerData: [],
      rowData: {},
      visible: false,
      disableds: true,
      visibleDrawer: false,
      visibleEdit: false,
      detailsFlag: false,
      collapse: false,
      infoId: null,
      position:null,
      editIds: [],
      topFilterInit: this.topFilterInitFun(),
      fetchapi: getListByPage,
      flterValue: {}, //参数
      columns: this.creatHeader(),
      fetchParams: { authStatus: 55031002,queryType:"check",
        xhrAbort: true}, //ipa 接口
      selectedRows: [], //选中服务中心
      dialogTitle: '选择车辆',
      visibleAdd: false,
      showImport:false,
      exportLoading:false,
      loading:false
    };
  },
  created() {
    this.chuqi();
  },
  methods: {
    batchExamine() {

      this.selectedRows.map((x) => {
        this.editIds.push({ authId: x.authId, vin:x.vin,status: 0 });
      });
      this.visibleEdit = true;
    },
    batchReject() {
      this.selectedRows.map((x) => {
        this.editIds.push({ authId: x.authId, status: 0 });
      });
      this.visibleEdit = true;
    },
    auditsave() {
      this.showImport = false;
      this.fetchParams = {...this.fetchParams};
    },
    downloadTemplate() {
      this.$confirm('此操作将下载excel模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true;
        downloadModel().then(res => {
          exportExcelFile(res.data, '批量驳回导入模板');
          this.exportLoading = false;
        });
      });
    },
    // Excel更新导入
    showImportFun() {
      this.showImport = true;
    },
    //     <multiuse-button size="mini" type="text"   onClick={() => this.Details(props.row)}>
    // 查看
    // </multiuse-button>
    //搜索数据
    topFilterInitFun() {
      return [
        {
          type: 'SELECT',
          label: '服务中心',
          render: (p) => {
            return (
              <div>
                <el-select v-model={this.selectDealerData} disabled={true} multiple placeholder="请选择">
                  {this.dealerData.map((item) => (
                    <el-option key={item.dealerCode} label={item.dealerShortname} value={item.dealerCompanyCode} />
                  ))}
                </el-select>
                <multiuse-button style="position: absolute;right: 0;height:100%" icon="el-icon-search" onClick={() => this.selectDelearFlag = true} />
              </div>
            );
          },
          onChange: val => {
            console.log(val)
          }
          // onInput: val => {
          //   // 修改store中 经销商名
          //   setStateParam('searchDealerName', val)
          //   // 重置store中 经销商code
          //   setStateParam('searchDealerCode', null)
          // }
        },
        { type: 'INPUT', label: '服务中心名称', fieldName: 'dealerName', placeholder: '请输入', initialValue: '' },
        { type: 'INPUT', label: '预授权单号', fieldName: 'authNo', placeholder: '请输入', initialValue: '' },
        // { type: 'INPUT', label: '维修工单号', fieldName: 'roNo', placeholder: '请输入', initialValue: '' },
        { type: 'INPUT', label: '车牌号', fieldName: 'licenseNo', placeholder: '请输入', initialValue: '' },
        {
          type: 'RANGE_DATE',
          label: '预授权申请日期',
          fieldName: 'beginApplyAt|endApplyAt',
          placeholder: '请输入',
          initialValue: [
            moment(new Date()).subtract(1,'months')
              .format("YYYY-MM-DD"),
            moment(new Date())
              .format("YYYY-MM-DD")
          ],
          rules: [{ required: true, message: '请选择日期', trigger: 'change' }]
        },
        { type: 'INPUT', label: '电机号', fieldName: 'engineNo', placeholder: '请输入', initialValue: '' },
        { type: 'INPUT', label: 'VIN', fieldName: 'vin', placeholder: '请输入', initialValue: '' },
        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'modelCode',
          placeholder: '请输入',
          initialValue: '',
          unitRender: (p) => {
            return (
              <div>
                <multiuse-button icon="el-icon-search" onClick={() => this.chooseOrderNo()} />
              </div>
            );
          },
        },
        {type: 'SELECT', label: '预授权类型', fieldName: 'authType', placeholder: '请选择预授权类型...', initialValue: '', itemList:this.createDictList('5508',[]), filterable: true},
        { type: 'INPUT', label: '主损件名称', fieldName: 'partName', placeholder: '请输入', initialValue: '' },
        { type: 'INPUT', label: '主损件代码', fieldName: 'partCode', placeholder: '请输入', initialValue: '' },
        { type: 'SELECT', label: '预授权状态', fieldName: 'authStatus', placeholder: '请选择', initialValue: '', itemList: this.createDictList('5503',[55031001,55031003,55031004,55031005,55031006,55031007]) },
      ];
    },
    //搜索获取数据
    changeHandle(val) {
      if(!val.beginApplyAt) {
        this.$notify.warning({ title: '提示信息', message: '申请开始日期不可为空！' });
        return
      }
      if(!val.endApplyAt) {
        this.$notify.warning({ title: '提示信息', message: '申请结束日期不可为空！' });
        return
      }
      if(getAppId() == 'arcfox') {
        if (moment(moment(val.endApplyAt).format('YYYY-MM-DD')).diff(moment(val.beginApplyAt), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '申请日期跨度不可超过十二个月！' });
          return
        }
      } else {
        if (moment(moment(val.endApplyAt).format('YYYY-MM-DD')).diff(moment(val.beginApplyAt), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '申请日期跨度不可超过十二个月！' });
          return
        }
      }
      let beginApplyAt = this.topFilterInit.find(x => x.fieldName == "beginApplyAt|endApplyAt").initialValue[0];
      let endApplyAt = this.topFilterInit.find(x => x.fieldName == "beginApplyAt|endApplyAt").initialValue[1];

      if(val.beginApplyAt) {
        val.beginApplyAt = moment(beginApplyAt).format('YYYY-MM-DD HH:mm:ss');
      }
      if(val.endApplyAt) {
        val.endApplyAt = moment(endApplyAt).format('YYYY-MM-DD HH:mm:ss');
      }
      this.fetchParams = Object.assign({}, this.fetchParams, val, { position:this.position,authStatus: 55031002 ,dealerCode: this.searchDealerCode, dealerCompanyCode: this.selectDealerData.length ? this.selectDealerData : null,
        empDealerData: this.empDealerData }, { xhrAbort: false });
      console.log('changeHandle=>', val);
      // this.SELECT();
    },
    //搜索获取数据

    resetHandle(val) {
      this.dealerData = [];
      this.selectDealerData = [];
      this.fetchParams = Object.assign({}, this.fetchParams, val, { position:this.position,dealerCompanyCode: null ,empDealerData: this.empDealerData}, { xhrAbort: false });
    },
    //服务中心选择页面
    SelectDelear() {
      this.selectDelearFlag = true;
    }, //关闭
    Delearclose() {
      this.selectDelearFlag = false;
    },
    //保存
    // Delearsave(obj) {
    //   this.topFilterInit.map((x) => {
    //     if ('ownerCode' == x.fieldName) {
    //       x.initialValue = obj[0].dealerCode; //维修工单号返显
    //     }
    //     // if ('ownerName' == x.fieldName) {
    //     //   x.initialValue = obj[0].dealerName; //维修工单号返显
    //     // }
    //   });
    //
    //   this.selectDelearFlag = false;
    // },
    //服务中心选择保存
    Delearsave(obj) {
      console.log('选择数据传递', obj);
      this.dealerData = obj;
      this.selectDealerData = [];
      obj.forEach(item => {
        this.selectDealerData.push(item.dealerCompanyCode);
      });
      this.selectDelearFlag = false;
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          fixed: 'left',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" disabled={props.row.authStatus == '55031002' ? false : true} onClick={() => this.edit(props.row)}>
                  审核
                </multiuse-button>
              </div>
            );
          },
        },
        { title: '服务中心代码', dataIndex: 'dealerCode', sorter: true },
        { title: '服务中心名称', dataIndex: 'dealerName', sorter: true },
        { title: '授权审核级别', dataIndex: 'levelName', sorter: true },
        { title: '下一审核级别', dataIndex: 'nextLevelName', sorter: true },
        { title: '预授权状态', dataIndex: 'statusStr', sorter: true },
        // { title: '预授权状态', dataIndex: 'authStatus', sorter: true, hidden: true },
        { title: '预授权单号', dataIndex: 'authNo', sorter: true },
        { title: '维修工单号', dataIndex: 'roNo', sorter: true },
        { title: 'VIN', dataIndex: 'vin', sorter: true },
        { title: '车牌号', dataIndex: 'licenseNo', sorter: true },
        { title: '车型名称', dataIndex: 'modelName', sorter: true },
        { title: '预授权类型', dataIndex: 'authTypeStr', sorter: true },
        // { title: '常规预授权分类', dataIndex: 'authSubStr', sorter: true },
        { title: '主损件代码', dataIndex: 'partCode', sorter: true },
        { title: '主损件名称', dataIndex: 'partName', sorter: true },
        // { title: '供应商', dataIndex: 'supName', sorter: true },
        { title: '行驶里程', dataIndex: 'driveMile', sorter: true },
        // { title: '发动机号/电机号', dataIndex: 'engineNo', sorter: true },
        { title: '故障现象代码', dataIndex: 'sysCode4', sorter: true },
        { title: '故障现象名称', dataIndex: 'sysName4', sorter: true },
        { title: '故障原因代码', dataIndex: 'frCode', sorter: true },
        { title: '故障原因名称', dataIndex: 'frName', sorter: true },
        // { title: '驳回次数', dataIndex: 'channelNum', sorter: true },
        { title: '费用合计', dataIndex: 'sumAmount', sorter: true ,precision: 2, numberFormat: true},
        { title: '工时费', dataIndex: 'labourAmount', sorter: true,precision: 2, numberFormat: true },
        { title: '备件费', dataIndex: 'partAmount', sorter: true ,precision: 2, numberFormat: true},
        { title: '附加费用', dataIndex: 'addAmount', sorter: true ,precision: 2, numberFormat: true},
        { title: '保修起始日期', dataIndex: 'repairBeginDate', sorter: true , dateFormat: 'yyyy-MM-dd'},
        { title: '保修截止日期', dataIndex: 'repairEndDate', sorter: true , dateFormat: 'yyyy-MM-dd'},
        // { title: '生产日期', dataIndex: 'prodDate', sorter: true , dateFormat: 'yyyy-MM-dd'},
        { title: '销售日期', dataIndex: 'saleDate', sorter: true, dateFormat: 'yyyy-MM-dd' },
        { title: '开单日期', dataIndex: 'roCreateDate', sorter: true, dateFormat: 'yyyy-MM-dd' },
        { title: '申请人', dataIndex: 'submitName', sorter: true },
        { title: '申请时间', dataIndex: 'applyAt', sorter: true, width: 140 },
        { title: '审核人', dataIndex: 'checkBy', sorter: true },
        { title: '审核时间', dataIndex: 'checkDate', sorter: true }
        // { title: '主键', dataIndex: 'authId', sorter: true, hidden: true },
      ];
    },

    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      this.disableds = this.selectedRows.length <= 0;
      console.log(this.selectedRows);
    },
    close() {
      this.visible = false;
    },
    chooseOrderNo() {
      this.visible = true;
    },
    async chuqi() {
      let res = await getPositionByUserOrgId(getUserOrgId());
      if (res.resultCode == 200) {
        this.position = res.data;
        if( this.position==10991001){
          let params={appId:getAppId()};
          let deaRes = await getDealerAttachListByUser(params);
          if (deaRes.resultCode == 200) {
            this.dealerCodes = deaRes.data.records;
            this.empDealerData = [];
            this.dealerCodes.forEach(item => {
              this.empDealerData.push(item.dealerCompanyCode);
            });
          }
        }
      }

    },
    save(obj) {
      this.topFilterInit.find((x) => x.fieldName == 'modelCode').initialValue = obj[0].modelCode;
      this.visible = false;
    },
    // 导出
  async  exportFileBtn() {
      // let json = Object.assign({}, { CODE: 'CODE_00000137' }, this.fetchParams);
      // let res = await exporturl(json);
      // if (res.resultCode == 200) {
      //   this.$router.push('/admin/auth/oem/downloadCenter');
      // }
      let beginApplyAt = this.topFilterInit.find(x => x.fieldName == "beginApplyAt|endApplyAt").initialValue[0];
      let endApplyAt = this.topFilterInit.find(x => x.fieldName == "beginApplyAt|endApplyAt").initialValue[1];
      if(!beginApplyAt) {
        this.$notify.warning({ title: '提示信息', message: '申请开始日期不可为空！' });
        return
      }
      if(!endApplyAt) {
        this.$notify.warning({ title: '提示信息', message: '申请结束日期不可为空！' });
        return
      }
      if(getAppId() == 'arcfox') {
        if (moment(moment(endApplyAt).format('YYYY-MM-DD')).diff(moment(beginApplyAt), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '申请日期跨度不可超过十二个月！' });
          return
        }
      } else {
        if (moment(moment(endApplyAt).format('YYYY-MM-DD')).diff(moment(beginApplyAt), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '申请日期跨度不可超过十二个月！' });
          return
        }
      }
      let obj = Object.assign({}, this.fetchParams,{ position:this.position,authStatus: 55031002 ,dealerCode: this.searchDealerCode, dealerCompanyCode: this.selectDealerData.length ? this.selectDealerData : null,
        empDealerData: this.empDealerData,xhrAbort: false});
      if(endApplyAt) {
        obj.beginApplyAt = moment(beginApplyAt).format('YYYY-MM-DD HH:mm:ss');
      }
      if(endApplyAt) {
        obj.endApplyAt = moment(endApplyAt).format('YYYY-MM-DD HH:mm:ss');
      }

      this.loading= true;
      getListForExport(obj).then((res) => {
        exportExcelFile(res.data, '预授权审核导出');
        this.loading= false;
      });
    },
    add() {
      this.visibleAdd = true;
    },
    closeAdd() {
      this.visibleAdd = false;
    },
    saveAdd() {
      this.visibleAdd = false;
      this.fetchParams = { ...this.fetchParams };
    },
    editclose() {
      this.visibleEdit = false;
    },
    detailClose() {
      this.detailsFlag = false;
    },
    detailSave() {
      this.detailsFlag = false;
      this.fetchParams = { ...this.fetchParams };
    },
    edit(val) {
      this.rowData = val;
      this.editIds = [];
      this.visibleEdit = true;
    },
    Details(val) {
      this.rowData = val;
      this.detailsFlag = true;
    },

    editsave() {
      this.visibleEdit = false;
      this.fetchParams = { ...this.fetchParams };
    },
  },
  // mounted() {
  //   this.BaseTable = this.$refs.listModal.$refs.pageTable;
  // }
};
</script>

<style lang="less" scoped></style>
